package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CarListAdapter;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.adapter.RouteListAdapter;
import com.example.administrator.yanfoxconn.bean.DNReform;
import com.example.administrator.yanfoxconn.bean.DNSpinner;
import com.example.administrator.yanfoxconn.bean.JVSchoolInfo;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.SwipeListViewOne;
import com.example.administrator.yanfoxconn.widget.SwipeListViewThree;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Song
 * on 2020/10/16
 * Description：人資校企合作 列表界面
 */
public class SchoolServiceListActivity extends BaseActivity implements View.OnClickListener,  DatePicker.OnDateChangedListener  {
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息回復
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_right)
    Button btnAdd;//新增

    @BindView(R.id.et_school_line)
    EditText etSchoolLine;//線別
    @BindView(R.id.et_school_name)
    EditText etSchoolName;//學校
    @BindView(R.id.et_window_code)
    EditText etWindowCode;//窗口
    @BindView(R.id.tv_date)
    TextView tvDate;//日期
    @BindView(R.id.btn_check)
    Button btnCheck;//查詢
    @BindView(R.id.lv_school_remark)
    SwipeListViewThree listView;

    private CarListAdapter carListAdapter;
private List<JVSchoolInfo> jvSchoolInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_school_service_lv);
        ButterKnife.bind(this);

        tvTitle.setText("查詢界面");
        btnBack.setOnClickListener(this);
        btnCheck.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        btnAdd.setText("新增");
        btnAdd.setVisibility(View.VISIBLE);
        tvDate.setOnClickListener(this);
            etWindowCode.setText(FoxContext.getInstance().getLoginId());
        date = new StringBuffer();
    }

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     *
     * @param listView
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        CarListAdapter  listAdapter = (CarListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    private void clickSeeOrAdd() {
        carListAdapter.setOnClickListenerGoOrAdd(new CarListAdapter.OnClickListenerGoOrAdd() {
            @Override
            public void OnClickListenerGo(int position) {//確認
                String name = URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName()));
                sign(name,jvSchoolInfoList.get(position).getS_NO());
            }

            @Override
            public void OnClickListenerAdd(int position) {//修改
                Intent intent = new Intent(SchoolServiceListActivity.this, SchoolReviseActivity.class);
                intent.putExtra("info", (Serializable) jvSchoolInfoList.get(position));
                startActivity(intent);
            }

            @Override
            public void OnClickListenerLook(int position) {//維護
                Intent intent = new Intent(SchoolServiceListActivity.this, SchoolPhotoActivity.class);
                intent.putExtra("info", (Serializable) jvSchoolInfoList.get(position));
                startActivity(intent);
            }

        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_check://查詢
                getList();
                break;
            case R.id.btn_title_right://新增
                Intent intent = new Intent(SchoolServiceListActivity.this,SchoolReleaseActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_date:
                initDateTime();
                show();
                break;
        }
    }
    private String url2 = "";

    public void getList() {

        try {
                String schoolLine = URLEncoder.encode(URLEncoder.encode(etSchoolLine.getText().toString(), "UTF-8"), "UTF-8");
                String schoolName = URLEncoder.encode(URLEncoder.encode(etSchoolName.getText().toString(), "UTF-8"), "UTF-8");
                String windowCode = URLEncoder.encode(URLEncoder.encode(etWindowCode.getText().toString(), "UTF-8"), "UTF-8");
                String date = URLEncoder.encode(URLEncoder.encode(tvDate.getText().toString(), "UTF-8"), "UTF-8");
                url2 = Constants.HTTP_RZXQ_GET_LIST + "?school_line=" + schoolLine + "&school_name=" + schoolName + "&window_code=" + windowCode + "&p_come_date=" + date;

                getListHandler(url2);

        Log.e("------url2------", url2);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void getListHandler(String url){
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        jvSchoolInfoList = new ArrayList<JVSchoolInfo>();

                        for (JsonElement type : array) {
                            JVSchoolInfo humi = gson.fromJson(type, JVSchoolInfo.class);
                            jvSchoolInfoList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }

    private void sign(String name,String sNo){
        showDialog();
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String url = Constants.HTTP_RZXQ_SIGN_OK+"?signer="+name+"&s_no="+sNo;
                String result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else {
                        Log.e("-----------", "result==" + result);
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(SchoolServiceListActivity.this,"成功");
//                    aboutAlert(msg.obj.toString(), MESSAGE_TOAST);
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(SchoolServiceListActivity.this, R.string.net_mistake);
                    break;
                case MESSAGE_SET_TEXT://進度賦值
                    carListAdapter = new CarListAdapter(SchoolServiceListActivity.this,jvSchoolInfoList,"school");
                    listView.setAdapter(carListAdapter);
                    setListViewHeightBasedOnChildren(listView);
                    clickSeeOrAdd();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type == MESSAGE_TOAST) {
//                            if (chongZuReformList != null) {
//                                chongZuReformList.clear();
//                                dnReformAdapter = new DNReformAdapter(SchoolServiceListActivity.this, chongZuReformList,FoxContext.getInstance().getType());
//                                listView.setAdapter(dnReformAdapter);
//                            }
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        getList();
    }
    private int year, month, day;
    private void initDateTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) ;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }
    private StringBuffer date, time;
    private void show(){
        AlertDialog.Builder builder = new AlertDialog.Builder(SchoolServiceListActivity.this);
        builder.setPositiveButton("確認", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (date.length() > 0) { //清除上次记录的日期
                    date.delete(0, date.length());
                    Log.e("--------","date.length()==="+date.length());
                }

                    tvDate.setText(date.append(String.valueOf(year)).append("-").append(String.valueOf(month+1)).append("-").append(day ));

                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvDate.setText("");
                dialog.dismiss();
            }
        });
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(SchoolServiceListActivity.this, R.layout.dialog_date, null);
        final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);
        dialog.setTitle("設置日期");
        dialog.setView(dialogView);
        dialog.show();
        //初始化日期监听事件
        datePicker.init(year, month, day, this);
    }
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.year = year;
        this.month = monthOfYear;
        this.day = dayOfMonth;

    }

}